<?php
session_start();
require_once 'db_connect.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '只允许POST请求']);
    exit;
}

try {
    $pdo = db_connect();
    
    // 获取POST数据
    $phone = trim($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    
    // 验证必填字段
    if (empty($phone) || empty($password)) {
        echo json_encode(['success' => false, 'message' => '手机号和密码不能为空']);
        exit;
    }
    
    // 验证手机号格式
    if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
        echo json_encode(['success' => false, 'message' => '手机号格式不正确']);
        exit;
    }
    
    // 查询用户
    $sql = "SELECT * FROM users WHERE phone = :phone AND status = 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['phone' => $phone]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user && $password==$user['password']) {
        // 登录成功，设置会话
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_phone'] = $user['phone'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['logged_in'] = true;
        
        echo json_encode([
            'success' => true,
            'message' => '登录成功',
            'redirect' => 'index.php'
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => '手机号或密码错误']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => '登录失败：' . $e->getMessage()]);
}
?>
